package com.yoshino.leetcode.oneHundred.one;

import java.util.Stack;

class MinStack {

    Stack<Long> stack;
    Long min;
    /** initialize your data structure here. */
    public MinStack() {
        stack = new Stack<>();
    }
    
    public void push(int x) {
        if (stack.isEmpty()) {
            stack.push(0L);
            min = Long.valueOf(x);
        } else {
            stack.push((long)(x - min));
            min = Math.min(x, min);
        }
    }
    
    public void pop() {
        if (stack.isEmpty()) {
            return;
        }
        if (stack.peek() < 0) {
            min -= stack.pop().intValue();
        } else {
            stack.pop();
        }
    }
    
    public int top() {
        if (stack.peek() > 0) {
            return (int)(stack.peek() + min);
        } else {
            return min.intValue();
        }
    }
    
    public int min() {
        return min.intValue();
    }
}